package org.k.vmmock;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.webapp.WebAppContext;
import org.k.vmmock.filter.ForwardFilter;
import org.k.vmmock.servlet.MockVelocityServlet;
import org.k.vmmock.util.Conf;
import org.k.vmmock.util.FileUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Created by hengxianwang on 16-10-29.
 */
public class Main {

    Server server;
    AtomicBoolean ab = new AtomicBoolean(false);
    /**
     * 创建WEB-INF文件夹
     * @param baseDir
     * @return
     */
    public boolean createWEBINF(File baseDir){
        boolean ret = false;
        try {
            FileUtils.createDir(baseDir, "WEB-INF");
            ret = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ret;
    }

    /**
     * copyJarFile2Local web.xml
     * @return
     */
    public boolean copyWebXml(){
        boolean ret = false;
        //WEB-INF/web.xml文件是否存在，存在覆盖
        try {
            FileUtils.copyJarFile2Local("web.xml", Conf.getBasePath(true) + Conf.get(Conf.WEB_XML_PATH));
            FileUtils.copyJarFile2Local("index.html", Conf.getBasePath(true) + "index.html");
            ret = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ret;
    }

    /**
     * 创建server.conf文件
     * @param baseDir
     * @return
     */
    public boolean createServerConf(File baseDir){
        boolean ret = false;
        try {
            FileUtils.createFile(baseDir, Conf.get(Conf.ROUTERS_FILE));
            ret = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ret;
    }

    /**
     * 创建page文件夹，放vm文件
     * @param baseDir
     * @return
     */
    public boolean createPageDir(File baseDir){
        boolean ret = false;
        try {
            FileUtils.createDir(baseDir, Conf.get(Conf.PAGE_DIR));
            ret = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ret;
    }

    /**
     * 创建test文件夹放mock数据
     * @param baseDir
     * @return
     */
    public boolean createTestDir(File baseDir){
        boolean ret = false;
        try {
            FileUtils.createDir(baseDir, Conf.get(Conf.TEST_DIR));
            ret = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ret;
    }

    /**
     * 初始化目录结构和文件
     * @return
     */
    public boolean init(){
        boolean ret = false;
        File baseDir = new File(Conf.basePath);

        if(!baseDir.exists()) baseDir.mkdir();

        ret = createWEBINF(baseDir);
        ret = copyWebXml();
        ret = createServerConf(baseDir);
        ret = createPageDir(baseDir);
        ret = createTestDir(baseDir);

        return ret;
    }

    /**
     * 启动jetty服务器
     * @param port
     * @throws Exception
     */
    public void startServer(int port) throws Exception {
        server = new Server(port);
        server.setStopAtShutdown(true);
        WebAppContext webAppContext = new WebAppContext();
        webAppContext.setContextPath("/");
        webAppContext.setResourceBase(Conf.basePath);
        webAppContext.setDescriptor(Conf.basePath + "/WEB-INF/web.xml");
        webAppContext.setDefaultsDescriptor("webdefault.xml");
        webAppContext.setParentLoaderPriority(true);
        webAppContext.addFilter(new FilterHolder(new ForwardFilter()), "/*", 1);
        webAppContext.addServlet(new ServletHolder(new MockVelocityServlet()),"*.vm");
        server.setHandler(webAppContext);

        server.start();
        server.join();
        ab.set(true);
    }

    public static void main(String[] args) throws Exception {

        final Main main = new Main();
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String cmd;
        while ((cmd = reader.readLine()) != null) {
            if(cmd.startsWith("start")){
                String[] cc = cmd.split("\\s+");
                if(cc.length < 3){
                    System.out.println("usage:java -jar vm-mock.jar path port");
                    continue;
                }
                String path = cc[1];
                final String port = cc[2];
                Conf.basePath = path;
                Conf.port = Integer.parseInt(port);

                main.init();
                System.out.println("init.................OK");


                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            main.startServer(Conf.port);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();

                while(main.ab.get()){
                    Thread.sleep(100);
                }
                System.out.println("start................OK");
            }else if(cmd.startsWith("stop")){
                if(main.server != null)
                    main.server.stop();
            }else if(cmd.startsWith("restart")){
                if(main.server.isStarted()){
                    continue;
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            main.startServer(Conf.port);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }else if(cmd.startsWith("exit")){
                if(main.server.isStarted())
                    main.server.stop();
                break;
            }else{
                System.out.println("unknown cmd");
            }
        }
        reader.close();

    }
}
